import { ref } from 'vue';   //引入ref
import { useEventListener } from './event'; //引入事件监听函数

// 监听滚动事件，主要用于数据列表滚动加载更多
// 按照惯例，组合式函数名以“use”开头
export function useScroll() {
    // 被组合式函数封装和管理的状态
    const scrollTop = ref(0);
    const scrollHeight = ref(0);
    const clientHeight = ref(0);

    useEventListener(window, 'scroll', (event) => {
        scrollTop.value = event.target.scrollingElement.scrollTop;
        scrollHeight.value = event.target.scrollingElement.scrollHeight;
        clientHeight.value = event.target.scrollingElement.clientHeight;

        isScrollBottom();
    })

    // 是否滚动到底部
    const scrollIsBottom = ref(true);

    // 判断是否滚动到底部
    function isScrollBottom() {
        if (scrollTop.value + clientHeight.value >= scrollHeight.value - 10) {
            scrollIsBottom.value = true;
        } else {
            scrollIsBottom.value = false;
        }
    }

    // 通过返回值暴露所管理的状态
    return { scrollIsBottom,scrollTop, scrollHeight, clientHeight };
}